﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;


namespace sqxt
{
    class expExcel
    {

        #region//导出excel,要添加savefiledialog控件
        public static void ExportData(DataGridView srcDgv, string fileName)//导出数据,传入一个datagridview和一个文件路径
        {
            string type = fileName.Substring(fileName.IndexOf(".") + 1);//获得数据类型
            if (type.Equals("xls", StringComparison.CurrentCultureIgnoreCase))//Excel文档
            {
                Excel.Application excel = new Excel.Application();
                try
                {
                    excel.DisplayAlerts = false;
                    excel.Workbooks.Add(true);
                    excel.Visible = false;

                    for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
                    {
                        excel.Cells[1, i + 1] = srcDgv.Columns[i].HeaderText;
                    }

                    for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
                    {
                        for (int j = 0; j < srcDgv.Columns.Count; j++)
                        {
                            if (srcDgv[j, i].ValueType.ToString() == "System.Byte[]")
                            {
                                excel.Cells[i + 2, j + 1] = "System.Byte[]";
                            }
                            else
                            {
                                excel.Cells[i + 2, j + 1] = srcDgv[j, i].Value;
                            }
                        }
                    }

                    excel.Workbooks[1].SaveCopyAs(fileName);//保存
                }
                finally
                {
                    excel.Quit();
                }
                return;
            }
        }

        #endregion
    }
}
